package com.queue.server.core;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.queue.common.message.Message;
import org.iq80.leveldb.DB;
import org.iq80.leveldb.Options;
import org.iq80.leveldb.impl.Iq80DBFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.File;


@Component
@ConfigurationProperties(prefix = "leveldb")
public class Leveldb {
    private DB db= null;

    private String folder;

    private String charset;

    /**
     * 初始化leveldb
     */
    public void initLeveldb(){
        Iq80DBFactory dbFactory = new Iq80DBFactory();
        Options options = new Options();
        //如果不存在则创建
        options.createIfMissing(true);
        try {
            db = dbFactory.open(new File(folder),options);
        }catch (Exception e){

        }
    }

    /**
     * 消息对象存入leveldb数据库
     * @param key
     * @param message
     */
    public void putMessage(Long key, Message message){
        byte[] messageByte = JSON.toJSONBytes(message, new SerializerFeature[]{SerializerFeature.DisableCircularReferenceDetect});
        try {
            db.put(String.valueOf(key).getBytes(charset),messageByte);
        }catch (Exception e){

        }
    }


}
